class Searcher
  include Ferret::Document
  
  INDEX_DIR = RAILS_ROOT + "/search_index"
  
  attr_accessor :index
  
  def initialize
    if !File.directory? INDEX_DIR
      Dir.mkdir INDEX_DIR
      @index = Ferret::Index::Index.new(:path => INDEX_DIR)
      create_index
    end
    
    @index = Ferret::Index::Index.new(:path => INDEX_DIR)      
  end
  
  def index_story(story)
    doc = Document.new
    doc << Field.new("id", story.id, Field::Store::YES, Field::Index::NO)
    doc << Field.new("title", story.title, Field::Store::YES, Field::Index::TOKENIZED) 
    doc << Field.new("url", story.url, Field::Store::YES, Field::Index::NO)
    @index << doc   
  end
  
  def query(query)
    docs = []
    results = @index.search(query)
    results.each do |id, score|
      doc = @index.doc(id)
      docs << doc
    end
    docs
  end
  
  def create_index
    stories = Story.find :all
    stories.each do |story|
      index_story story  
    end  
  end
  
  
    
end